﻿using AspectCore.Extensions.Autofac;
using Autofac;
using Cyss.Core;
using Cyss.Core.Api;
using Cyss.Core.Api.Client;
using Cyss.Core.AutoMapper;
using Cyss.Core.Cache;
using Cyss.Core.Infrastructure;
using Cyss.Core.Librarys;
using Cyss.Core.RabbitMQ;
using Cyss.Core.Repository;
using Cyss.Core.Repository.EF;
using Microsoft.EntityFrameworkCore;
using Order.Api.Controllers;
using Order.Api.Services.Mapping;
using System;

namespace Order.Api.Infrastructure
{

    /// <summary>
    /// IOC 注册
    /// </summary>
    public class DependencyRegistrar : IDependencyRegistrar
    {
        /// <summary>
        /// Register services and interfaces
        /// </summary>
        /// <param name="builder">Container builder</param>
        public void Register(ContainerBuilder builder)
        {

            builder.Register(c =>
            {
                var optionsBuilder = new DbContextOptionsBuilder<OrderObjectContext>();
                optionsBuilder.UseSqlServer(c.Resolve<OrderConnectionString>().Value, builder =>
                {
                    builder.EnableRetryOnFailure(maxRetryCount: 5, maxRetryDelay: TimeSpan.FromSeconds(30), errorNumbersToAdd: new int[] { 2 });
                });
                return optionsBuilder.Options;
            }).InstancePerLifetimeScope();

            builder.Register(context => new OrderObjectContext(context.Resolve<DbContextOptions<OrderObjectContext>>()))
                   .As<IDbContext>().InstancePerLifetimeScope();

            builder.RegisterGeneric(typeof(EfRepository<>)).As(typeof(IRepository<>)).InstancePerLifetimeScope();
            builder.RegisterAllService();

 
            builder.RegisterType<DefaultCreateOrUpdateName>().As<IDefaultCreateOrUpdateName>().SingleInstance();
            builder.RegisterType<DefaultLogging>().As<ILogging>().SingleInstance();
            builder.RegisterType<DefaultClientLogging>().As<IClientLogging>().SingleInstance();
            builder.RegisterType<DefaultRequestLogging>().As<IRequestLogging>().SingleInstance();

            builder.RegisterType<ApiToken>().As<IApiToken>().SingleInstance();

            builder.RegisterDynamicProxy();

            var controllerBaseType = typeof(OrderBaseApiController);
            builder.RegisterAssemblyTypes(typeof(Program).Assembly)
                .Where(x => controllerBaseType.IsAssignableFrom(x) && x != controllerBaseType).PropertiesAutowired();


        }



    }
}
